import datetime
import logging
import time
import urllib
from urllib import request, parse
import ssl
import json
import playsound

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
f_handler = logging.FileHandler('trace1.log')
f_handler.setLevel(logging.INFO)
f_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d] - %(message)s"))
logger.addHandler(f_handler)

# context = ssl._create_unverified_context()

url_getMultiReserveTime = "https://maicai.api.ddxq.mobi/order/getMultiReserveTime"

uid = "6254e70eadeb2f0001f9e65f"  # 用户号，从Fiddler中抓取
station_id = "6108f66781ff030001369967"  # 站点好，小程序首页中选中自家地址后，再从Fiddler抓取
session_id = "554bfdd0f747271ea1183ac73fbf890a"  # session_id
cookie = f"DDXQSESSID={session_id}"  # 登录后，从Fiddler抓取

products = [[{"type":1,"id":"598803b6916edffe450e2900","price":"13.50","count":1,"description":"","sizes":[],"cart_id":"598803b6916edffe450e2900","parent_id":"","parent_batch_type":-1,"category_path":"58f9e574936edfe4568b5789,58fb3a67936edf89778b57d1","manage_category_path":"201,205,206","activity_id":"","sku_activity_id":"","conditions_num":"","product_name":"卡士3.3原味鲜酪乳三联杯 100g*3杯","product_type":0,"small_image":"https://img.ddimg.mobi/product/69d3d82591a131599723418126.jpg!deliver.product.list","total_price":"13.50","origin_price":"13.50","total_origin_price":"13.50","no_supplementary_price":"13.50","no_supplementary_total_price":"13.50","size_price":"0.00","buy_limit":0,"price_type":0,"promotion_num":0,"instant_rebate_money":"0.00","is_invoice":1,"sub_list":[],"is_booking":0,"is_bulk":0,"view_total_weight":"组","net_weight":"300","net_weight_unit":"ml","storage_value_id":2,"temperature_layer":"0~4℃","sale_batches":{"batch_type":-1},"is_shared_station_product":0,"is_gift":0,"supplementary_list":[],"order_sort":4,"is_presale":0}]]
print("testing alert sound...")
playsound.playsound("alert3.mp3")
print("done")

postDict = {
    "uid": uid,
    "longitude": "121.425446",
    "latitude": "31.237419",
    "station_id": station_id,
    "city_number": "0101",
    "api_version": "9.49.2",
    "app_version": "2.82.4",
    "applet_source": "",
    "channel": "applet",
    "app_client_id": "4",
    "sharer_uid": "",
    "s_id": session_id,
    "openid": "osP8I0WwHO78fDdWv6vaJWMVXZFg",
    "h5_source": "",
    "time": 1649930135,
    "device_token": "WHJMrwNw1k/FKPjcOOgRd+J1ee6rW3n/PRrH6Kq8m9g66TlQ+UvE66AmDe51vPg9Mc/XtPI0QeUz7MbJchBByraRk0jv7nINFdCW1tldyDzmauSxIJm5Txg==1487582755342",
    "address_id": "5eb951e9c7316f5e8b9e79c9",
    "group_config_id": "",
    "products": products,
    "isBridge": "false",
    "nars": "013d110af8e9e08b667fc6b1c128a4bd",
    "sesi": "wRoAbPz88f6ce1a7d83d288a960cda5e9645f5a"
}
headers = {
    "Host": "maicai.api.ddxq.mobi",
    "content-type": "application/x-www-form-urlencoded",
    # "Connection": "keep-alive",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat",
    "ddmc-api-version": "9.49.2",
    "ddmc-app-client-id": "4",
    "ddmc-build-version": "2.82.4",
    "ddmc-channel": "applet",
    "ddmc-city-number": "0101",
    "ddmc-device-id": "osP8I0WwHO78fDdWv6vaJWMVXZFg",
    "ddmc-ip": "",
    "ddmc-latitude": "31.237419",
    "ddmc-longitude": "121.425446",
    "ddmc-os-version": "[object Undefined]",
    "ddmc-station-id": station_id,
    "ddmc-time": 1649930135,
    "ddmc-uid": uid,
    "Referer": "https://servicewechat.com/wx1e113254eda17715/422/page-frame.html",
    # "Accept-Encoding": "gzip, deflate, br",
    "Cookie": cookie
}
request = urllib.request.Request(url=url_getMultiReserveTime, headers=headers)
data_string = urllib.parse.urlencode(postDict)
last_data = bytes(data_string, encoding='utf-8')


def time_cmp(first_time, second_time):
    print(first_time)
    print(second_time)
    return int(time.strftime("%H%M%S", first_time)) - int(time.strftime("%H%M%S", second_time))


while True:
    now = datetime.datetime.now()
    now_time = datetime.datetime.strptime(now.strftime('%H:%M:%S'), '%H:%M:%S')
    open_time = datetime.datetime.strptime('6:20:00', '%H:%M:%S')
    close_time = datetime.datetime.strptime('22:00:00', '%H:%M:%S')
    # current_time = time.localtime(time.time())
    # if ((current_time.tm_hour >= 5) and (current_time.tm_min >= 59) and (current_time.tm_sec >= 57)):
    # if current_time.tm_hour >= 5:
    if open_time < now_time < close_time:
        try:
            response = urllib.request.urlopen(request, data=last_data)
            json_resp = json.loads(response.read().decode("utf-8"))
            logger.info(json_resp)
            data_list = json_resp["data"]
            assert len(data_list) is not None
            data = data_list[0]
            if "closed" in data and data["closed"]:
                print("今日已打烊，请明日再来吧~")
            else:
                date_list = data["time"]
                assert len(date_list) > 0
                date = date_list[0]
                time_list = date["times"]
                assert len(time_list) > 0
                first_time = time_list[0]
                if first_time["fullFlag"]:
                    print("k", end="", flush=True)
                else:
                    print(f"\n{now.strftime('%Y-%m-%d %H:%M:%S')} 有运力拉！！！冲鸭！！！")
                    playsound.playsound("alert1.mp3")
                    print(date_list)
                    print(time_list)
        except Exception as ex:
            print("error found...")
            print(ex)
            logger.error(ex)
        time.sleep(10)
    else:
        print(".", end="", flush=True)
        time.sleep(1)